<?php
declare(strict_types=1);

namespace app\command;

use think\console\Command;
use think\console\Input;
use think\console\Output;
use app\model\Order;
use app\service\LogService;

class SyncOrderStatus extends Command
{
    protected function configure()
    {
        $this->setName('sync:order_status')
            ->setDescription('Sync express order status');
    }
    
    protected function execute(Input $input, Output $output)
    {
        try {
            // 获取需要同步的订单
            $orders = Order::where('status', 'in', [1, 2, 3]) // 待揽收、已揽收、运输中
                ->where('update_time', '<', time() - 1800) // 30分钟未更新
                ->select();
            
            $count = 0;
            foreach ($orders as $order) {
                try {
                    // 调用快递100接口查询物流状态
                    $response = $this->queryExpressStatus($order->express_no);
                    
                    // 更新订单状态
                    if ($response['status']) {
                        $order->status = $response['status'];
                        $order->save();
                        $count++;
                    }
                } catch (\Exception $e) {
                    LogService::error('SyncOrderStatus', sprintf(
                        'Order sync failed: %s, order_no: %s',
                        $e->getMessage(),
                        $order->order_no
                    ));
                    continue;
                }
            }
            
            $output->writeln(sprintf('Synced %d orders status', $count));
        } catch (\Exception $e) {
            LogService::error('SyncOrderStatus', sprintf(
                'Sync order status failed: %s',
                $e->getMessage()
            ));
            $output->writeln('<error>' . $e->getMessage() . '</error>');
        }
    }
    
    protected function queryExpressStatus($expressNo)
    {
        // TODO: 实现快递100接口调用
        return ['status' => 0];
    }
} 